// src/pages/QuizPage.jsx
import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import apiClient from '../api/axios';
import LoadingSpinner from '../components/LoadingSpinner';

function QuizPage() {
    const { id } = useParams(); // 知识点ID
    const navigate = useNavigate();

    const [knowledgePoint, setKnowledgePoint] = useState(null);
    const [question, setQuestion] = useState(null);
    const [selectedOption, setSelectedOption] = useState('');
    const [studentAnswer, setStudentAnswer] = useState(''); // 用于简答题
    const [result, setResult] = useState(null); // { isCorrect: boolean, explanation: string }
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState('');

    // 1. 加载知识点内容
    useEffect(() => {
        const fetchKp = async () => {
            try {
                const response = await apiClient.get(`/knowledge-points/${id}`);
                setKnowledgePoint(response.data);
                setIsLoading(false);
            } catch (error) {
                console.error(error);
                setError('加载知识点失败: ' + error.message);
                setIsLoading(false);
            }
        };
        if (id) {
            fetchKp();
        } else {
            setIsLoading(false);
        }
    }, [id]);

    // 2. 获取题目 (在知识点加载后)
    const fetchQuestion = async (difficulty, type = 'single-choice') => {
        if (!knowledgePoint) return;
        setIsLoading(true);
        setQuestion(null);
        setResult(null);
        setSelectedOption('');
        setStudentAnswer('');
        try {
            // 添加一个小延迟，让用户看到加载状态
            await new Promise(resolve => setTimeout(resolve, 300));
            
            const response = await apiClient.post('/ai/generate-question', {
                knowledgePointContent: knowledgePoint.content,
                difficulty: difficulty,
                type: type
            });
            setQuestion(response.data);
        } catch (error) {
            console.error(error);
            setError('生成题目失败: ' + (error.response?.data?.message || error.message));
        } finally {
            setIsLoading(false);
        }
    };
    
    // 3. 提交答案
    const handleSubmit = async (e) => {
        e.preventDefault();
        
        if (question.type === 'single-choice' && !selectedOption) {
            alert('请选择一个答案！');
            return;
        }
        
        if (question.type === 'short-answer' && !studentAnswer.trim()) {
            alert('请输入你的答案！');
            return;
        }
        
        try {
            if (question.type === 'single-choice') {
                // 选择题直接评分
                const isCorrect = selectedOption === question.answer;
                setResult({
                    isCorrect: isCorrect,
                    explanation: question.explanation
                });

                // 如果回答错误，自动将知识点加入复习列表
                if (!isCorrect) {
                    updateReviewStatus(true);
                }
            } else if (question.type === 'short-answer') {
                // 简答题调用AI评分
                setIsLoading(true);
                const response = await apiClient.post('/ai/grade-answer', {
                    question: question,
                    studentAnswer: studentAnswer
                });
                
                setResult(response.data);
                
                // 如果回答错误，自动将知识点加入复习列表
                if (!response.data.isCorrect) {
                    updateReviewStatus(true);
                }
                
                setIsLoading(false);
            }
        } catch (error) {
            console.error(error);
            setError('评分失败: ' + (error.response?.data?.message || error.message));
            setIsLoading(false);
        }
    };

    const updateReviewStatus = async (needsReview) => {
        try {
            await apiClient.put(`/knowledge-points/${id}`, { reviewList: needsReview });
        } catch (error) {
            console.error("更新复习状态失败", error);
        }
    };

    if (isLoading) return (
      <div style={{ padding: '20px', maxWidth: '1000px', margin: '0 auto' }}>
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center', 
          marginBottom: '1rem' 
        }}>
          <h1>📝 知识点测评</h1>
          <button 
            onClick={() => navigate('/')} 
            style={{ 
              padding: '8px 16px', 
              backgroundColor: '#6c757d', 
              color: 'white', 
              border: 'none', 
              borderRadius: '4px', 
              cursor: 'pointer'
            }}
          >
            ← 返回主页
          </button>
        </div>
        <LoadingSpinner message="AI正在智能出题中，请稍候..." useGame={true} />
      </div>
    );
    
    if (error) return <div style={{ padding: '20px', color: 'red' }}>错误: {error}</div>;
    if (!knowledgePoint) return <div style={{ padding: '20px' }}>未找到知识点</div>;

    return (
        <div style={{ padding: '20px', maxWidth: '1000px', margin: '0 auto' }}>
            <div style={{ 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center', 
                marginBottom: '1rem' 
            }}>
                <h1>📝 知识点测评: {knowledgePoint.title}</h1>
                <button 
                    onClick={() => navigate('/')} 
                    style={{ 
                        padding: '8px 16px', 
                        backgroundColor: '#6c757d', 
                        color: 'white', 
                        border: 'none', 
                        borderRadius: '4px', 
                        cursor: 'pointer'
                    }}
                >
                    ← 返回主页
                </button>
            </div>
            
            <div style={{ 
                marginBottom: '20px', 
                padding: '20px', 
                backgroundColor: '#e3f2fd', 
                borderRadius: '8px',
                boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
            }}>
                <h3>🎯 选择题目难度和类型:</h3>
                <div style={{ 
                    display: 'flex', 
                    gap: '10px', 
                    flexWrap: 'wrap',
                    marginTop: '15px'
                }}>
                    <button 
                        onClick={() => fetchQuestion('基础', 'single-choice')} 
                        style={{ 
                            padding: '10px 20px',
                            backgroundColor: '#4CAF50',
                            color: 'white',
                            border: 'none',
                            borderRadius: '4px',
                            cursor: 'pointer',
                            fontWeight: 'bold'
                        }}
                    >
                        基础-选择题
                    </button>
                    <button 
                        onClick={() => fetchQuestion('中等', 'single-choice')} 
                        style={{ 
                            padding: '10px 20px',
                            backgroundColor: '#FF9800',
                            color: 'white',
                            border: 'none',
                            borderRadius: '4px',
                            cursor: 'pointer',
                            fontWeight: 'bold'
                        }}
                    >
                        中等-选择题
                    </button>
                    <button 
                        onClick={() => fetchQuestion('困难', 'single-choice')} 
                        style={{ 
                            padding: '10px 20px',
                            backgroundColor: '#F44336',
                            color: 'white',
                            border: 'none',
                            borderRadius: '4px',
                            cursor: 'pointer',
                            fontWeight: 'bold'
                        }}
                    >
                        困难-选择题
                    </button>
                    <button 
                        onClick={() => fetchQuestion('基础', 'short-answer')} 
                        style={{ 
                            padding: '10px 20px',
                            backgroundColor: '#4CAF50',
                            color: 'white',
                            border: 'none',
                            borderRadius: '4px',
                            cursor: 'pointer',
                            fontWeight: 'bold'
                        }}
                    >
                        基础-简答题
                    </button>
                    <button 
                        onClick={() => fetchQuestion('中等', 'short-answer')} 
                        style={{ 
                            padding: '10px 20px',
                            backgroundColor: '#FF9800',
                            color: 'white',
                            border: 'none',
                            borderRadius: '4px',
                            cursor: 'pointer',
                            fontWeight: 'bold'
                        }}
                    >
                        中等-简答题
                    </button>
                    <button 
                        onClick={() => fetchQuestion('困难', 'short-answer')} 
                        style={{ 
                            padding: '10px 20px',
                            backgroundColor: '#F44336',
                            color: 'white',
                            border: 'none',
                            borderRadius: '4px',
                            cursor: 'pointer',
                            fontWeight: 'bold'
                        }}
                    >
                        困难-简答题
                    </button>
                </div>
            </div>
            
            <hr style={{ margin: '30px 0', borderColor: '#ddd' }} />

            {question && !result && (
                <form onSubmit={handleSubmit} style={{ 
                    marginBottom: '20px',
                    padding: '20px',
                    backgroundColor: '#f8f9fa',
                    borderRadius: '8px',
                    boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                }}>
                    <h2 style={{ 
                        marginTop: 0,
                        color: '#333'
                    }}>
                        {question.question}
                    </h2>
                    
                    {question.type === 'single-choice' ? (
                        <div style={{ marginBottom: '20px' }}>
                            {Object.entries(question.options).map(([key, value]) => (
                                <div 
                                    key={key} 
                                    style={{ 
                                        marginBottom: '15px',
                                        padding: '15px',
                                        backgroundColor: selectedOption === key ? '#e3f2fd' : '#fff',
                                        borderRadius: '4px',
                                        border: selectedOption === key ? '2px solid #2196F3' : '1px solid #ddd',
                                        cursor: 'pointer'
                                    }}
                                    onClick={() => setSelectedOption(key)}
                                >
                                    <label style={{ 
                                        display: 'flex', 
                                        alignItems: 'center', 
                                        cursor: 'pointer',
                                        margin: 0
                                    }}>
                                        <input
                                            type="radio"
                                            name="option"
                                            value={key}
                                            checked={selectedOption === key}
                                            onChange={(e) => setSelectedOption(e.target.value)}
                                            style={{ 
                                                marginRight: '15px',
                                                transform: 'scale(1.3)'
                                            }}
                                        />
                                        <span style={{ fontSize: '1.1rem' }}>
                                            <strong>{key}.</strong> {value}
                                        </span>
                                    </label>
                                </div>
                            ))}
                        </div>
                    ) : (
                        <div style={{ marginBottom: '20px' }}>
                            <label htmlFor="studentAnswer" style={{ 
                                display: 'block', 
                                marginBottom: '10px',
                                fontSize: '1.1rem',
                                fontWeight: 'bold'
                            }}>
                                ✍️ 你的答案:
                            </label>
                            <textarea
                                id="studentAnswer"
                                value={studentAnswer}
                                onChange={(e) => setStudentAnswer(e.target.value)}
                                rows={8}
                                style={{ 
                                    width: '100%', 
                                    padding: '15px', 
                                    borderRadius: '4px', 
                                    border: '1px solid #ddd',
                                    fontSize: '16px',
                                    fontFamily: 'Arial, sans-serif',
                                    resize: 'vertical'
                                }}
                                placeholder="请输入你的答案..."
                            />
                        </div>
                    )}
                    
                    <button 
                        type="submit" 
                        style={{ 
                            padding: '12px 30px', 
                            backgroundColor: '#2196F3', 
                            color: 'white', 
                            border: 'none', 
                            borderRadius: '4px', 
                            cursor: 'pointer',
                            fontSize: '16px',
                            fontWeight: 'bold'
                        }}
                    >
                        📤 提交答案
                    </button>
                </form>
            )}

            {result && (
                <div style={{ 
                    padding: '30px', 
                    borderRadius: '8px', 
                    backgroundColor: result.isCorrect ? '#e8f5e9' : '#ffebee',
                    border: `2px solid ${result.isCorrect ? '#4CAF50' : '#f44336'}`,
                    boxShadow: '0 4px 8px rgba(0,0,0,0.1)'
                }}>
                    <h2 style={{ 
                        marginTop: 0,
                        textAlign: 'center'
                    }}>
                        🎯 测评结果
                    </h2>
                    <div style={{ 
                        textAlign: 'center',
                        margin: '20px 0'
                    }}>
                        <span style={{ 
                            color: result.isCorrect ? '#4CAF50' : '#f44336', 
                            fontWeight: 'bold', 
                            fontSize: '24px'
                        }}>
                            {result.isCorrect ? '✅ 回答正确！' : '❌ 回答错误！'}
                        </span>
                    </div>
                    
                    {question.type === 'single-choice' ? (
                        <div style={{ 
                            textAlign: 'center',
                            margin: '20px 0',
                            padding: '15px',
                            backgroundColor: '#fff',
                            borderRadius: '4px'
                        }}>
                            <p style={{ 
                                fontSize: '18px',
                                margin: '0'
                            }}>
                                <strong>正确答案是: {question.answer}</strong>
                            </p>
                        </div>
                    ) : null}
                    
                    <div style={{ 
                        padding: '20px',
                        backgroundColor: '#fff',
                        borderRadius: '4px',
                        margin: '20px 0'
                    }}>
                        <h3 style={{ 
                            marginTop: 0,
                            color: '#333'
                        }}>
                            💡 解释:
                        </h3>
                        <p style={{ 
                            fontSize: '16px',
                            lineHeight: '1.6',
                            margin: '0'
                        }}>
                            {result.explanation}
                        </p>
                    </div>
                    
                    {!result.isCorrect && (
                        <div style={{ 
                            textAlign: 'center',
                            padding: '15px',
                            backgroundColor: '#fff3e0',
                            borderRadius: '4px',
                            margin: '20px 0',
                            color: '#f57c00'
                        }}>
                            <p style={{ 
                                fontWeight: 'bold',
                                margin: '0',
                                fontSize: '18px'
                            }}>
                                ⚠️ 该知识点已加入你的复习列表。
                            </p>
                        </div>
                    )}
                    
                    <div style={{ 
                        marginTop: '30px', 
                        display: 'flex', 
                        gap: '15px',
                        justifyContent: 'center'
                    }}>
                        <button 
                            onClick={() => fetchQuestion(question.difficulty, question.type)} 
                            style={{ 
                                padding: '12px 25px', 
                                backgroundColor: '#4CAF50', 
                                color: 'white', 
                                border: 'none', 
                                borderRadius: '4px', 
                                cursor: 'pointer',
                                fontSize: '16px',
                                fontWeight: 'bold'
                            }}
                        >
                            🔁 再来一题
                        </button>
                        <button 
                            onClick={() => navigate('/')} 
                            style={{ 
                                padding: '12px 25px', 
                                backgroundColor: '#f44336', 
                                color: 'white', 
                                border: 'none', 
                                borderRadius: '4px', 
                                cursor: 'pointer',
                                fontSize: '16px',
                                fontWeight: 'bold'
                            }}
                        >
                            🏠 返回主页
                        </button>
                    </div>
                </div>
            )}
        </div>
    );
}

export default QuizPage;